/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.ui.dataimportwiz;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import who.tmap.bo.Attrs;
import who.tmap.common.TMapException;
import who.tmap.imp.ExcelImportAdapter;
import who.tmap.imp.ImportAdapter;
import who.tmap.imp.impl.ImportAdapterFactory;
import who.tmap.ui.util.FileChooserFilter;
import who.tmap.ui.util.MiscUIHelper;
import who.tmap.ui.util.jsorttable.JSortTable;
import who.tmap.ui.util.jsorttable.SortTableModel;

/**
 * @author stl
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class JFrameExcelImportWizard extends JInternalFrame implements DataImportWizardFrame {
   
    protected Attrs table;
    
    private JInternalFrame thisFrame =this;
    
	private JPanel jContentPane = null;

	private JLabel jLabelWorkSheet = null;
	private JPanel jPanel = null;
	private JLabel jLabelFileName = null;

	private JButton jButtonFileName = null;
	private JPanel jPanelTable = null;
	private JTable jTable1 = null;
	private JScrollPane jScrollPane = null;
	private JPanel jPanelMisc = null;
	private DataWizardTableDataModel dataModel =null;
	
	private JComboBox jComboBoxWorkSheet = null;
	
	private JButton jButtonRefresh = null;
	private JCheckBox jCheckBoxFirstRowCFN = null;

	private JLabel jLabelFile = null;
	/**
	 * This is the default constructor
	 */
	public JFrameExcelImportWizard() {
		super();
		initialize();
	}
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setContentPane(getJContentPane());
		pack();
	}
	
	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());

			jContentPane.add(getJPanel(), java.awt.BorderLayout.CENTER);
		}
		return jContentPane;
	}
	
	/**
	 * This method initializes jLabelWorkSheet
	 * 
	 * @return javax.swing.JLabel
	 */
	private JLabel getJLabelWorkSheet() {
		if(jLabelWorkSheet == null) {
			jLabelWorkSheet = new JLabel();
			jLabelWorkSheet.setText("Work sheet");
		}
		return jLabelWorkSheet;
	}
	
	/**
	 * This method initializes jLabelFileName
	 * 
	 * @return JLabel
	 */
	private JLabel getJLabelFileName() {
		if(jLabelFileName == null) {
			jLabelFileName = new JLabel();
			jLabelFileName.setText("File name");
		}
		return jLabelFileName;
	}	
	
	/**
	 * This method initializes jPanel
	 * 
	 * @return JPanel
	 */
	private JPanel getJPanel() {
		if(jPanel == null) {
			jPanel = new JPanel();
			
			jPanel.setLayout(new BorderLayout());
			jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
			
			jPanel.add(getJPanelMisc(), BorderLayout.NORTH);
			jPanel.add(getJPanelTable(), BorderLayout.CENTER);	
		}
		return jPanel;
	}
	
	private ImportAdapter connectToAdapter() throws TMapException {
        ImportAdapter adapter =(ExcelImportAdapter)ImportAdapterFactory.getInstance().getImportAdapter( ImportAdapterFactory.EXCEL );
        
        Map<String, String> config =new TreeMap<String, String>();
        config.put( ExcelImportAdapter.FILE_NAME, getJLabelFile().getText() );
        config.put( ExcelImportAdapter.WORK_SHEET, ( getJComboBoxWorkSheet().getSelectedItem() != null ) ? getJComboBoxWorkSheet().getSelectedItem().toString() : "" );
        config.put( ExcelImportAdapter.FIRST_ROW_CONTAINS_FIELD_NAMES, Boolean.toString( jCheckBoxFirstRowCFN.isSelected() ) );
        
        adapter.configure( config );	
        
        adapter.connect();
        
        return adapter;
	}
	
	public void populateDsProperties( Map<String, String> dsProperties ) throws Exception {
		getJLabelFile().setText( dsProperties.get( ExcelImportAdapter.FILE_NAME ) );
		getJComboBoxWorkSheet().setSelectedItem( dsProperties.get( ExcelImportAdapter.WORK_SHEET ) );
		jCheckBoxFirstRowCFN.setSelected( Boolean.parseBoolean( dsProperties.get( ExcelImportAdapter.FIRST_ROW_CONTAINS_FIELD_NAMES ) ) );
		
		populateSampleData();
	}
	
	@SuppressWarnings("unchecked")
	public void populateWorkSheets() throws TMapException {
        ExcelImportAdapter adapter =null;
        
        try {
            adapter =(ExcelImportAdapter)connectToAdapter();            
            Set workSheets =adapter.getWorkSheets();
            jComboBoxWorkSheet.removeAllItems();
            
            Iterator it =workSheets.iterator();
            while( it.hasNext() ) {
                jComboBoxWorkSheet.addItem( (String)it.next() );
            }
            
        } catch( Exception e ) {
            throw new TMapException( e );
        } finally {
            if ( adapter != null ) {
                adapter.disconnect();
            }
        }	    
	}
	
	public void populateSampleData() throws TMapException {
        ImportAdapter adapter =connectToAdapter();
        
        try {
            table =adapter.readSampleData();
            dataModel.setAttrs( table );
            dataModel.fireTableStructureChanged();
            
        } catch( Exception e ) {
            throw new TMapException( e );
        } finally {
            adapter.disconnect();
        }
	}
	
	public Attrs getTable() {
	    return table;
	}

	/**
	 * This method initializes jButtonFileName	
	 * 	
	 * @return JButton	
	 */    
	public JButton getJButtonFileName() {
		if (jButtonFileName == null) {
			jButtonFileName = new JButton();
			jButtonFileName.setText("Select...");
			jButtonFileName.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
					JFileChooser fileChooser = new JFileChooser();
					fileChooser.addChoosableFileFilter( new FileChooserFilter( FileChooserFilter.EXCEL_EXT ) );
					fileChooser.setCurrentDirectory( FileChooserFilter.DATA_DIR );
			
					// Open file dialog.
					int retVal =fileChooser.showOpenDialog(	getContentPane() );
					
					if ( retVal == JFileChooser.APPROVE_OPTION ) {

					    getJLabelFile().setText( fileChooser.getSelectedFile().getAbsolutePath() );
					     
					    try {
                            populateWorkSheets();
                        } catch (TMapException e1) {
                            new MiscUIHelper().displayErrorMessage( thisFrame, e1 );
                        }
					}
				}
			});
		}
		return jButtonFileName;
	}
	/**
	 * This method initializes jPanelTable	
	 * 	
	 * @return JPanel	
	 */    
	private JPanel getJPanelTable() {
		if (jPanelTable == null) {
			GridLayout gridLayout4 = new GridLayout(1,1);
			jPanelTable = new JPanel();
			jPanelTable.setLayout(gridLayout4);
			jPanelTable.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
			
			gridLayout4.setRows(1);
			jPanelTable.add(getJScrollPane(), null);
		}
		return jPanelTable;
	}
	
	/**
	 * This method initializes jTable1	
	 * 	
	 * @return JTable	
	 */    
	private JTable getJTable1() {
		if (jTable1 == null) {
			jTable1 = new JTable();
			
			dataModel = new DataWizardTableDataModel();
			jTable1 =new JSortTable( (SortTableModel)dataModel );			
		} 
		return jTable1;
	}
	
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return JScrollPane	
	 */    
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTable1());
		}
		return jScrollPane;
	}
	
	/**
	 * This method initializes jPanelMisc	
	 * 	
	 * @return JPanel	
	 */    
	private JPanel getJPanelMisc() {
		if (jPanelMisc == null) {
			GridLayout gridLayout = new GridLayout( 3, 3 );

			jPanelMisc = new JPanel( gridLayout );
			gridLayout.setHgap(5);
			gridLayout.setVgap(5);
			jPanelMisc.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
			
			jPanelMisc.add(getJLabelFileName(), null);
			jPanelMisc.add(getJLabelFile(), null);
			jPanelMisc.add(getJButtonFileName(), null);
			jPanelMisc.add(getJLabelWorkSheet(), null);
			jPanelMisc.add(getJComboBoxWorkSheet(), null);
			jPanelMisc.add(getJButtonRefresh(), null);
			jPanelMisc.add(getJCheckBoxFirstRowCFN(), null);
		}
		return jPanelMisc;
	}
	
	/**
	 * This method initializes jComboBoxWorkSheet	
	 * 	
	 * @return JComboBox	
	 */    
	private JComboBox getJComboBoxWorkSheet() {
		if (jComboBoxWorkSheet == null) {
			jComboBoxWorkSheet = new JComboBox();
			/*jComboBoxWorkSheet.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
				    try {
                        populateSampleData();
                    } catch (TMapException e1) {

                        e1.printStackTrace();
                    }
				}
			})*/;
		}
		return jComboBoxWorkSheet;
	}
	
	/**
	 * This method initializes jButtonRefresh	
	 * 	
	 * @return JButton	
	 */    
	private JButton getJButtonRefresh() {
		if (jButtonRefresh == null) {
			jButtonRefresh = new JButton();
			jButtonRefresh.setText("Apply");
			jButtonRefresh.addActionListener(new java.awt.event.ActionListener() { 
				public void actionPerformed(java.awt.event.ActionEvent e) {    
				    try {
                        populateSampleData();
                    } catch (TMapException e1) {
                        new MiscUIHelper().displayErrorMessage( thisFrame, e1 );
                    }
				}
			});
		}
		return jButtonRefresh;
	}
	
	/**
	 * This method initializes jCheckBoxFirstRowCFN	
	 * 	
	 * @return JCheckBox	
	 */    
	private JCheckBox getJCheckBoxFirstRowCFN() {
		if (jCheckBoxFirstRowCFN == null) {
			jCheckBoxFirstRowCFN = new JCheckBox();
			jCheckBoxFirstRowCFN.setText("Field names in 1st row");
		}
		return jCheckBoxFirstRowCFN;
	}
	
	/**
	 * This method initializes jTextFieldFileName	
	 * 	
	 * @return JTextField	
	 */    
	public JLabel getJLabelFile() {
		if (jLabelFile == null) {
			jLabelFile = new JLabel("");
		}
		return jLabelFile;
	}
	
	public Attrs getValuesTable() throws TMapException {
	    Attrs table =null;
	    ImportAdapter adapter =connectToAdapter();
        
        try {
            table =adapter.readValues();

        } catch( Exception e ) {
            throw new TMapException( e );
        } finally {
            if ( adapter != null ) {
                adapter.disconnect();
            }
        }
        
        return table;
	}
	
 }  //  @jve:decl-index=0:visual-constraint="10,36"
